package com.heima.article.service.ServiceImpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult load(Short loadType, ArticleHomeDto dto) {
        //校验参数
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            //判断本页面显示文章数量大小的size 若为空或者0 则置为10
            size = 10;
        }
        // 将size和最大页面大小的50进行比较 size小于等于最大值则返回size 否则返回最大值
        //保证页面最大的显示大小为50以内
        size = Math.min(size, MAX_PAGE_SIZE);
        dto.setSize(size);
        //校验参数类型
        if (!loadType.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadType.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            //如果参数类型不为1 并且参数类型不等于2
            loadType = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //文章频道校验
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间校验
        if(dto.getMaxBehotTime() ==null){
            dto.setMaxBehotTime(new Date());
        }
        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        //查询数据 获取文章列表集合
        List<ApArticle> apArticlesList = apArticleMapper.loadArticleList(dto, loadType);
        //封装返回结果
        ResponseResult responseResult=ResponseResult.okResult(apArticlesList);
        return responseResult;
    }
}